package com.cloudcc.mobile.view.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.CApplication;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.MenuFillEvent;
import com.cloudcc.cloudframe.bus.EventList.UpdateUserEvent;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.bus.MessageNumX;
import com.cloudcc.cloudframe.model.MenuModel;
import com.cloudcc.cloudframe.model.MenuTabModel;
import com.cloudcc.cloudframe.model.UserModel;
import com.cloudcc.cloudframe.net.async.AsyncClient;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrClassicDefaultHeader;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrClassicFrameLayout;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrDefaultHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrHandler;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.AppManager;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.MenuAdapter;
import com.cloudcc.mobile.adapter.MyMenuAdapter;
import com.cloudcc.mobile.bull.GongniuCheckinActivity;
import com.cloudcc.mobile.dao.CallLogDao;
import com.cloudcc.mobile.dao.PushEngine;
import com.cloudcc.mobile.dao.impl.CallLogDaoImpl;
import com.cloudcc.mobile.dao.impl.PushEngineImpl;
import com.cloudcc.mobile.db.ApprovalDB;
import com.cloudcc.mobile.db.ChatMessageDB;
import com.cloudcc.mobile.db.DraftBoxDB;
import com.cloudcc.mobile.db.EventDB;
import com.cloudcc.mobile.db.MessageDB;
import com.cloudcc.mobile.db.PushSaveMessageDB;
import com.cloudcc.mobile.db.TaskDB;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.cloudcc.mobile.entity.JurisdictionEntity;
import com.cloudcc.mobile.entity.ModuleMessage;
import com.cloudcc.mobile.entity.PushSaveMessage;
import com.cloudcc.mobile.entity.Qxbeau;
import com.cloudcc.mobile.event.BeauEventList;
import com.cloudcc.mobile.im.IMHelper;
import com.cloudcc.mobile.im.utils.PreferenceManager;
import com.cloudcc.mobile.manager.CacheManager;
import com.cloudcc.mobile.manager.CloudCCPushManager;
import com.cloudcc.mobile.manager.ConfigManager;
import com.cloudcc.mobile.manager.ContactsManager;
import com.cloudcc.mobile.manager.MenuManager;
import com.cloudcc.mobile.manager.OrmManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.messagecent.BeauTongzhi;
import com.cloudcc.mobile.messagecent.TongzhiImpl;
import com.cloudcc.mobile.presenter.MainUIPresenter;
import com.cloudcc.mobile.presenter.PushPresenter;
import com.cloudcc.mobile.presenter.UserPresenter;
import com.cloudcc.mobile.search.SearchActivity;
import com.cloudcc.mobile.service.BindingService;
import com.cloudcc.mobile.service.DingWeiService;
import com.cloudcc.mobile.util.DialogUtils;
import com.cloudcc.mobile.util.FileUtil;
import com.cloudcc.mobile.util.ImageUtils;
import com.cloudcc.mobile.util.ToastUtil;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.UserUtils;
import com.cloudcc.mobile.view.activity.CallLogActivity;
import com.cloudcc.mobile.view.activity.MapsActivity;
import com.cloudcc.mobile.view.activity.Myinformation;
import com.cloudcc.mobile.view.activity.SelectPicActivity;
import com.cloudcc.mobile.view.activity.SelectPictureActivity;
import com.cloudcc.mobile.view.activity.TaskManagementActivty;
import com.cloudcc.mobile.view.aduit.AduitNearByMapActivity;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.base.SlidingRightAdapter;
import com.cloudcc.mobile.view.dynamic.SendTimeLineActivity;
import com.cloudcc.mobile.view.dynamic.dynamic.DynamicMainFragment;
import com.cloudcc.mobile.view.login.LoginNewActivity;
import com.cloudcc.mobile.view.main.fragment.MainMessageFragment;
import com.cloudcc.mobile.view.main.fragment.MainUIFragment;
import com.cloudcc.mobile.view.main.fragment.NewCoworkerListFragment;
import com.cloudcc.mobile.view.main.fragment.Newmainmefragments;
import com.cloudcc.mobile.view.main.fragment.SettingFragment;
import com.cloudcc.mobile.view.mymodel.data;
import com.cloudcc.mobile.view.nearby.NearByMapActivity;
import com.cloudcc.mobile.view.schedule.ScheduleMainActivity;
import com.cloudcc.mobile.view.web.NewWebView;
import com.cloudcc.mobile.view.web.NewWebViewActivity;
import com.cloudcc.mobile.weight.DialogUtils.DialogOnClickListener;
import com.cloudcc.mobile.weight.DialogUtilsZhuXiao;
import com.cloudcc.mobile.weight.MyExpandableListView;
import com.dk.view.drop.CoverManager;
import com.easemob.EMCallBack;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.google.gson.Gson;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.litesuits.android.log.Log;
import com.mypage.utils.BadgeUtil;
import com.mypage.utils.SaveTemporaryData;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.update.UmengDialogButtonListener;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UpdateStatus;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.cloudcc.cloudframe.CApplication.mPushAgent;

/**
 * 主页
 *
 * @author wangzhiqiang
 * @date 2015-6-15 下午1:11:39
 */

/**
 * @author seven
 */
@SuppressLint("SetJavaScriptEnabled")
public class MainUIActivity extends BaseActivity implements
        OnChildClickListener, IEventLife, OnClickListener, EMEventListener, PtrHandler {
    private int mFrom;
    private LinearLayout contaxt, me, xiaoxi, zhuye,
            footer_cooperation_container;
    public LinearLayout menu_foot;
    private ImageView contaxt_image, locationImg, photoimag, me_image,
            xiaoxi_image, index_image, zhuye_img, footer_cooperation_icon;
    private TextView phototext, qiandaotext, messagenum, tvCompanyName,
            contaxt_text, tvUserName, me_Text, xiaoxi_Text, zhuye_text,
            footer_cooperation_text;
    private LinearLayout menuri, mean_dai, fujin,jihe;
    private ImageView menuUserLogo;
    private LinearLayout aboutPersion;
    private List<Fragment> fragments = new ArrayList<Fragment>();
    private ArrayList<ModuleMessage> list;
    private MenuAdapter adapter;
    private MyMenuAdapter mMenuAdapter;
    private SlidingMenu menu;
    private String picPath;
    private int currentTab = -1;
    private LinearLayout qiandaolla;
    private LinearLayout callLog, renwu, shijian, shichang;
    private MyMessageReceiver receiver;
    public Bitmap photo;
    public static Bitmap imgphoto;
    private LinearLayout menuSetting, menuHome;
    private TextView menu_index_name;
    private String mEn = RunTimeManager.getInstance().getlanguage();
    private ApprovalDB db4;
    /**
     * slidemenu 下面的菜单
     */
    MyExpandableListView module_list;
    private long num;
    private WebView webview;
    private int mGroupPosition = -101;
    private int mChildPosition = -102;
    int expandFlag = -100;// 控制列表的展开
    private int sign = -1;// 控制group只能打开一个

    private MainUIPresenter mPresenter = new MainUIPresenter();
    private UserPresenter userPresenter = new UserPresenter();

    private static MenuModel ccMenu;
    private LinearLayout sm_sousuo_kuang;
    public static MainUIActivity instance;
    private CallLogDao callLogDao;//请求服务器的封装方法类
    private int jurisdiction = 1;//权限 ：1 所有 2查看 3没有
    private String qxyuntie;
    private String tongshiShow = RunTimeManager.getInstance().getTongshi();

    //下拉刷新
    public PtrClassicFrameLayout xlsx_x_bsr;
    public ListView xmListview;
    private List<PushSaveMessage> messsageList = new ArrayList<>();
    public SlidingRightAdapter tzadapter_x;

    private RelativeLayout shouyeyindao;
    private RelativeLayout tongshiyindao;
    private RelativeLayout yuntieyindao;
    private LinearLayout meyindao;
    private TongzhiImpl tongzhiImpl = new TongzhiImpl();
    private BeauEventList.BeauTongzhiEvent event;
    private boolean tongshiydao = true, meydao = true, yuntieydao = true, shouyeydao = true;//同事和我的界面引导是否被关闭，默认未关闭
    SharedPreferences yindaoShare;//记录是否第一次登陆，是否需要引导
    ToastUtil toast;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        yindaoShare = getSharedPreferences("NearByYinDao", 0);
        shouyeydao = yindaoShare.getBoolean("shouyeydao", true);
        tongshiydao = yindaoShare.getBoolean("tongshiydao", true);
        meydao = yindaoShare.getBoolean("meydao", true);
        yuntieydao = yindaoShare.getBoolean("yuntieydao", true);
        shouyeyindao = (RelativeLayout) findViewById(R.id.shouyeyindao);
        if (shouyeydao) {
            shouyeyindao.setVisibility(View.VISIBLE);
        } else {
            shouyeyindao.setVisibility(View.GONE);
        }
        shouyeyindao.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = yindaoShare.edit();
                editor.putBoolean("shouyeydao", false);
                editor.commit();
                shouyeydao = false;
                shouyeyindao.setVisibility(View.GONE);
            }
        });
        tongshiyindao = (RelativeLayout) findViewById(R.id.tongshiyindao);
        tongshiyindao.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = yindaoShare.edit();
                editor.putBoolean("tongshiydao", false);
                editor.commit();
                tongshiydao = false;
                tongshiyindao.setVisibility(View.GONE);
            }
        });
        meyindao = (LinearLayout) findViewById(R.id.yindaomainme);
        meyindao.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = yindaoShare.edit();
                editor.putBoolean("meydao", false);
                editor.commit();
                meydao = false;
                meyindao.setVisibility(View.GONE);
            }
        });
        yuntieyindao = (RelativeLayout) findViewById(R.id.yuntieyindao);
        yuntieyindao.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = yindaoShare.edit();
                editor.putBoolean("yuntieydao", false);
                editor.commit();
                yuntieydao = false;
                yuntieyindao.setVisibility(View.GONE);
            }
        });
        instance = this;
        toast = new ToastUtil(getApplicationContext());
        initMessage();

        register();
        setHttp();

        mActivityFrom = getIntent().getIntExtra("activity.from", -1);
        mFrom = getIntent().getIntExtra("froms", -1);
        getJurisdiction();
        try {
            initCoverManager();// 信息提示气泡管理器
        } catch (Exception e) {
        }
        try {
            initMenu();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            setMessageNum();
            initPushAndLocat();
        } catch (Exception e) {
            Tools.handle(e);
        }
        try {
            isFenxiang();// 是否分享
            initPage();
            addListener();
            tvUserName.setText(UserManager.getManager().getUser().userName);
            Log.d("tvUserName", UserManager.getManager().getUser().userName
                    + "  " + UserManager.getManager().getUser().orgName);
            tvCompanyName.setText(UserManager.getManager().getUser().orgName);

        } catch (Exception e) {
            e.printStackTrace();
        }
        // 登录小网页 test 暂时每次都登录
        if (mActivityFrom == 2) {
            loginWebView();
        }

        // 聊天IM
        loginIM();

        // 登陆成功了 设置 不是第一次登录
        UserManager.getManager().saveFrist(false);

        //推送注册监听
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                CApplication.tokens = deviceToken;

                if (UserManager.getManager().isLogin()) {
                    CApplication.isTokenPush = false;
                    new PushPresenter().registerBind(CApplication.tokens);
                }
            }

            @Override
            public void onFailure(String s, String s1) {

            }
        });

        initUpdate();
        initRequestDataTz();
        initRefreshTz();
        initMessageNum();
    }

    private void getJurisdiction() {
        callLogDao = new CallLogDaoImpl();
        BeauEventList.JurisdictionEvent event = new BeauEventList.JurisdictionEvent();
        callLogDao.getJurisdiction("003", event);
    }


    public void onEventMainThread(BeauEventList.JurisdictionEvent event) {
        if (event.isError()) {
            return;
        }
        JurisdictionEntity jurisdictionEntity = event.getData();
        if (jurisdictionEntity.query == true) {
            if (jurisdictionEntity.add == true) {
                jurisdiction = 1;
            } else {
                jurisdiction = 2;
            }
        } else {
            jurisdiction = 3;
        }

        if (jurisdiction == 3) {
            callLog.setVisibility(View.GONE);
        }
    }


    private void initUpdate() {
        UmengUpdateAgent.setUpdateOnlyWifi(false);
        UmengUpdateAgent.setDeltaUpdate(false);
        UmengUpdateAgent.setDialogListener(new UmengDialogButtonListener() {
            @Override
            public void onClick(int status) {
                switch (status) {
                    case UpdateStatus.NotNow:
                        AppManager.getInstance().AppExitOld();
                        AppManager.getInstance().AppExit();
                        break;
                }

            }
        });
        UmengUpdateAgent.update(this);
    }

    public void onEventMainThread(UpdateUserEvent event) {
        String message = "更换头像";
        if (event.isOk()) {
            message += "成功";
        } else {
            message += "失败";
        }
        imgphoto = ImageUtils.toRoundBitmap(UserManager.getManager().getLogo());
        menuUserLogo.setImageBitmap(imgphoto);
        Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
    }

    private void fillUser() {
        tvCompanyName.setText(UserManager.getManager().getUser().orgName);
        String userId = UserManager.getManager().getUser().userId;
        String url = UrlTools.getTopImage(userId);
        UserUtils.setLogoRound_z(url, menuUserLogo, UserUtils
                        .getBackGroudColorByUserIdHash(userId, mContext), UserUtils
                        .getNickRowName(UserManager.getManager().getUser().userName),
                mContext);
    }

    public void onEventMainThread(MenuToggleEvent event) {
        if (menu == null) {
            return;
        }
        if (event.isToggle) {
            menu.showSecondaryMenu();
            initRequestDataTz();
            if (event.open) {
            }
        } else {
            menu.toggle();
            module_list.expandGroup(slidingtag);
        }
    }

    //消息数据刷新
    public void onEventMainThread(MessageNumX event) {
        setChatMessageNum();
        refreshMessageTz();
    }

    @Override
    public int getLayoutId() {
        return R.layout.act_main;
    }

    /**
     * 初始化 消息提示
     */
    private void initCoverManager() {
        // 消息条数的提示 消息清除动画
        CoverManager.getInstance().init(this);
        CoverManager.getInstance().setMaxDragDistance(150);
        CoverManager.getInstance().setExplosionTime(150);
    }

    /**
     * 是否是分享
     */
    private void isFenxiang() {
        if (AppContext.isFenXiang) {
            Intent intent = new Intent(this, SendTimeLineActivity.class);
            startActivity(intent);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // super.onSaveInstanceState(outState);
    }

    private void addListener() {
        /**
         * 点击签到
         */
        qiandaotext.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
              /*  Intent intent = new Intent(MainUIActivity.this,
                        MapsActivity.class);
                startActivity(intent);*/

                Intent intent = new Intent(MainUIActivity.this,
                        GongniuCheckinActivity.class);
                startActivity(intent);
                menu.toggle();
            }
        });

        qiandaolla.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                /*Intent intent = new Intent(MainUIActivity.this,
                        MapsActivity.class);
                startActivity(intent);*/
                  Intent intent = new Intent(MainUIActivity.this,
                        GongniuCheckinActivity.class);
                startActivity(intent);

//                menu.toggle();
            }
        });

        /**
         *通话记录
         */
        callLog.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                menu.toggle();
                Intent intent = new Intent(MainUIActivity.this,
                        CallLogActivity.class);
                intent.putExtra("jurisdiction", jurisdiction);
                startActivity(intent);
            }
        });
        /**
         *任务跳转
         */
        renwu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent(MainUIActivity.this, NewWebViewActivity.class);
                intent2.putExtra("MyPushMessageReceiver", "task");
                startActivity(intent2);

            }
        });
        /**
         *事件跳转
         */
        shijian.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainUIActivity.this, NewWebViewActivity.class);
                intent.putExtra("MyPushMessageReceiver", "event");
                startActivity(intent);
            }
        });
        /**
         *应用市场跳转
         */
        shichang.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                menu.toggle();
                Intent intent = new Intent(MainUIActivity.this,
                        NewWebView.class);
                AppContext.urlString = "http://appstore.cloudcc.com";
                startActivity(intent);
            }
        });

        /**
         *附近
         */
        fujin.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                menu.toggle();//收起侧滑栏
//                if(!Tools.isCN(MainUIActivity.this) && Tools.isGooglePlayServiceAvailable(MainUIActivity.this)){//如果不在国内并且支持google服务，跳转google地图的附近
//                    Intent intent = new Intent(MainUIActivity.this,
//                            NearByGoogleMapActivity.class);
//                    startActivity(intent);
//                }else{
                    Intent intent = new Intent(MainUIActivity.this,
                            NearByMapActivity.class);
                    startActivity(intent);
//                }
            }
        });

        /**
         *稽核管理
         */
        jihe.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(RunTimeManager.getInstance().getProfileId().equals("aaa2018895D59EFXHtAk")
                ||RunTimeManager.getInstance().getProfileId().equals("aaa202077AB493FrpD5U")) {
                    menu.toggle();//收起侧滑栏
                    Intent intent = new Intent(MainUIActivity.this,
                            AduitNearByMapActivity.class);
                    startActivity(intent);
//                }
                }
                else {
                    Toast.makeText(mContext, R.string.qxtx, Toast.LENGTH_SHORT).show();
                }
            }
        });

        /**
         * 待审批
         */


        mean_dai.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

//                    db4.deleteApprovalAll();
                AppContext.urlString = UrlManager.getRootUrl()
                        + "/WeiXin_getmangeAllAppRequest.action";
                Intent intent2 = new Intent(mContext, TaskManagementActivty.class);
                intent2.putExtra("MyPushMessageReceiver", "approval");
//                    Intent intent = new Intent(AppContext.DAISHENPI_NUM);
//                    mContext.sendBroadcast(intent);
                // Intent intent2 = new Intent(context,
                // TaskManagementActivty.class);
                startActivity(intent2);

            }
        });

        /**
         * 日程事件
         */
        sm_sousuo_kuang.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, SearchActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("sort.filter", (Serializable) menusend);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        menuri.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(mContext, ScheduleMainActivity.class);
                startActivity(intent);
            }
        });

        /**
         * 改变头像
         */
        photoimag.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainUIActivity.this,
                        SelectPictureActivity.class);
                startActivityForResult(intent, 70);
            }
        });
        /**
         * 签到
         */
        locationImg.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainUIActivity.this,
                        MapsActivity.class);
                startActivity(intent);
                menu.toggle();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        Log.d("activityresultcode", resultCode + "  " + requestCode);
        if (resultCode == Activity.RESULT_OK && requestCode == 70) {
            // imageView不设null, 第一次上传成功后，第二次在选择上传的时候会报错。
            picPath = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH);
            File temp = new File(picPath);
            startPhotoZoom(Uri.fromFile(temp));

        } else if (resultCode == Activity.RESULT_OK && requestCode == 3) {
            menuUserLogo.setImageBitmap(null);
            if (data != null) {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    photo = extras.getParcelable("data");
                    imgphoto = ImageUtils.toRoundBitmap(photo);
                    menuUserLogo.setImageBitmap(imgphoto);
                    UserManager.getManager().saveLogo(photo);
                    userPresenter.UpdateLogo(photo, UserManager.getManager()
                            .getUser());
                }
            } else {
                byte[] imagebyte = ImageUtils.readSdcard(picPath);
                photo = ImageUtils.loadBitmap(imagebyte, 100, 100);
                imgphoto = ImageUtils.toRoundBitmap(photo);
                menuUserLogo.setImageBitmap(imgphoto);
                userPresenter.UpdateLogo(photo, UserManager.getManager()
                        .getUser());
            }
        }
    }

    // 初始化菜单
    private void initMenu() {
        menu = new SlidingMenu(this);
        menu.setMode(SlidingMenu.LEFT_RIGHT);
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE); // 触摸边界拖出菜单
//        menu.setShadowDrawable(R.drawable.shadow);//设置阴影图片												// 取消滑动SlidingMenu.TOUCHMODE_NONE,打开滑动SlidingMenu.TOUCHMODE_FULLSCREEN
//		menu.setShadowWidthRes(R.dimen.shadow_width);
        menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        menu.setOffsetFadeDegree(0.4f);

        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        View view = LayoutInflater.from(this).inflate(R.layout.menu_item_new,
                null);
        menu.setMenu(view);
        //右滑菜单
        View viewR = LayoutInflater.from(this).inflate(R.layout.activity_base_sliding_right,
                null);
        menu.setSecondaryMenu(viewR);
        mean_dai = (LinearLayout) findViewById(R.id.mean_dai);
        fujin = (LinearLayout) findViewById(R.id.fujin);
        //新增稽核管理
        jihe = (LinearLayout) findViewById(R.id.jihe);
        menuri = (LinearLayout) findViewById(R.id.menu_ri);
        sm_sousuo_kuang = (LinearLayout) findViewById(R.id.sm_sousuo_kuang);
        menuUserLogo = (ImageView) view.findViewById(R.id.userimg);

        aboutPersion = (LinearLayout) view.findViewById(R.id.userinfo);
        intentAbout();
//        menuUserLogo.setOnClickListener(this);
        tvUserName = (TextView) view.findViewById(R.id.name);
        tvCompanyName = (TextView) view.findViewById(R.id.menu_gongsi);
        phototext = (TextView) view.findViewById(R.id.phototext);
        qiandaolla = (LinearLayout) findViewById(R.id.qiandaoll);
        callLog = (LinearLayout) findViewById(R.id.call_log);
        renwu = (LinearLayout) findViewById(R.id.menu_renwu);
        shijian = (LinearLayout) findViewById(R.id.menu_shijian);
        //应用市场隐藏
        shichang = (LinearLayout) findViewById(R.id.menu_shichang);
        shichang.setVisibility(View.GONE);

        phototext.setOnClickListener(this);
        qiandaotext = (TextView) view.findViewById(R.id.qiandaotext);
        tvCompanyName = (TextView) view.findViewById(R.id.menu_gongsi);
        photoimag = (ImageView) view.findViewById(R.id.titleimag);
        locationImg = (ImageView) view.findViewById(R.id.locationImg);
        menuHome = (LinearLayout) view.findViewById(R.id.shouye_menu);// 首页按钮
        menuHome.setOnClickListener(this);
        menuSetting = (LinearLayout) view.findViewById(R.id.shezhi_menu);
        menuSetting.setOnClickListener(this);
        module_list = (MyExpandableListView) view
                .findViewById(R.id.module_list);
        menu_index_name = (TextView) view.findViewById(R.id.menu_index_name);
        //右侧侧滑初始化
        xlsx_x_bsr = (PtrClassicFrameLayout) viewR.findViewById(R.id.xlsx_x_bsr);
        xmListview = (ListView) viewR.findViewById(R.id.messagee_lv_x);

        if (jurisdiction == 3) {
            callLog.setVisibility(View.GONE);
        }

        fillUser();

        requestFromCache();
        requestFromNet();
    }

    /**
     * 从本地获取
     */
    private void requestFromCache() {
        List<MenuModel> menus = CacheManager.getInstance().getMenu();
        if (!ListUtils.isEmpty(menus)) {
            fillMenu(false, menus);
        }

    }

    /**
     * 从网络获取
     */
    private void requestFromNet() {
        mPresenter.getMenus();
    }

    private TextView drop, drop99;

    /**
     * 获取控件
     *
     * @throws DbException
     */
    private Context context;

    private void initPage() {
        fragments.add(new MainUIFragment());
        fragments.add(new MainMessageFragment());
        fragments.add(new DynamicMainFragment());
//		fragments.add(new CoworkerListFragment());
        fragments.add(new NewCoworkerListFragment());
        fragments.add(new Newmainmefragments());
        // fragments.add(new MainMeFragment());
        fragments.add(new SettingFragment());
        // fragments.add(new WebFragment());
        getSupportFragmentManager().beginTransaction()
                .add(R.id.frame, fragments.get(2)).commit();


        zhuye = (LinearLayout) findViewById(R.id.chat_zhuye);
        contaxt = (LinearLayout) findViewById(R.id.chat_contaxt);
        if ("true".equals(tongshiShow)) {
            contaxt.setVisibility(View.VISIBLE);
        } else {
            contaxt.setVisibility(View.GONE);
        }
        xiaoxi = (LinearLayout) findViewById(R.id.chat_xiaoxi);
        footer_cooperation_container = (LinearLayout) findViewById(R.id.footer_cooperation_container);
        me = (LinearLayout) findViewById(R.id.chat_me);
        menu_foot = (LinearLayout) findViewById(R.id.menu_foot);
        index_image = (ImageView) findViewById(R.id.index_image);
        footer_cooperation_icon = (ImageView) findViewById(R.id.footer_cooperation_icon);
        contaxt_image = (ImageView) findViewById(R.id.contaxt_image);
        xiaoxi_image = (ImageView) findViewById(R.id.xiaoxi_image);
        me_image = (ImageView) findViewById(R.id.me_image);
        // drop = (WaterDrop)findViewById(R.id.drop);
        drop = (TextView) findViewById(R.id.drop);
        drop99 = (TextView) findViewById(R.id.drop99);
        zhuye_text = (TextView) findViewById(R.id.index_text);
        xiaoxi_Text = (TextView) findViewById(R.id.xiaoxi_Text);
        me_Text = (TextView) findViewById(R.id.me_Text);
        contaxt_text = (TextView) findViewById(R.id.contaxt_text);
        footer_cooperation_text = (TextView) findViewById(R.id.footer_cooperation_text);

        xiaoxi.setVisibility(View.GONE);
        if ((RunTimeManager.getInstance().getOrgId().toString()).equals("cc2016082668512dceVM")) {//金山特殊处理
            footer_cooperation_container.setVisibility(View.GONE);
            contaxt.setVisibility(View.GONE);
        }
        if ((RunTimeManager.getInstance().getOrgId().toString()).equals("cc201506240qbuYv624")) {//科华特殊处理
            footer_cooperation_container.setVisibility(View.GONE);
            contaxt.setVisibility(View.GONE);
        }

        zhuye.setOnClickListener(new MyOnClickListener(0));// 主页
        xiaoxi.setOnClickListener(new MyOnClickListener(1));// 消息
        footer_cooperation_container
                .setOnClickListener(new MyOnClickListener(2));// 协作
        contaxt.setOnClickListener(new MyOnClickListener(3));// 同事
        me.setOnClickListener(new MyOnClickListener(4));// 关于我

        index_image.setOnClickListener(new MyOnClickListener(0));
        xiaoxi_image.setOnClickListener(new MyOnClickListener(1));
        footer_cooperation_icon.setOnClickListener(new MyOnClickListener(2));
        contaxt_image.setOnClickListener(new MyOnClickListener(3));
        me_image.setOnClickListener(new MyOnClickListener(4));

        zhuye_text.setOnClickListener(new MyOnClickListener(0));
        xiaoxi_Text.setOnClickListener(new MyOnClickListener(1));
        footer_cooperation_text.setOnClickListener(new MyOnClickListener(2));
        contaxt_text.setOnClickListener(new MyOnClickListener(3));
        me_Text.setOnClickListener(new MyOnClickListener(4));
        // 默认显示第一页
        setSelect(0);
        tabSelect(0);
        // 注册广播
        receiver = new MyMessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(AppContext.MESSAGE_DAISHENPI);
        filter.addAction(AppContext.MESSAGE_DAIBANRENWU);
        filter.addAction(AppContext.MESSAGE_RICHENG_EVENT);
        filter.addAction(AppContext.MESSAGE_CHATMESSAGE);
        filter.addAction(AppContext.MESSAGE_SYSTEM);
        filter.addAction(AppContext.UPDATE_USER_ICON);
        filter.addAction(AppContext.MESSAGE_SYSTEM_NUM);
        filter.addAction(AppContext.TASK_NUM);
        filter.addAction(AppContext.DAISHENPI_NUM);
        filter.addAction(AppContext.CAOGAO_NUM);
        filter.addAction(AppContext.EVENT_NUM);
        filter.addAction(AppContext.MESSAGE_CHAT_NUM);
        filter.addAction(AppContext.OPEN_FILE);
        filter.addAction(AppContext.WEB_TO_MENU);
        filter.addAction(AppContext.GET_WEIXIN_LOGIN);
        registerReceiver(receiver, filter);

        // setChatMessageNum();
        try {
            setMessageNum();
            setChatMessageNum();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置未读消息条数
     *
     * @throws DbException
     */
    private void setMessageNum() throws DbException {
        // 设置消息数量
        MessageDB db = new MessageDB(mContext, UserManager.getManager()
                .getUser().userId + "message");
        long messnum = db.getNewMessageNum();
        DraftBoxDB db2 = new DraftBoxDB(mContext, UserManager.getManager()
                .getUser().userId + "box.db");
        long draftnum = db2.getNewDraftBoxNum();
        TaskDB db3 = new TaskDB(mContext,
                UserManager.getManager().getUser().userId + "chat");
        long tasknum = db3.getNewTaskNum();
        ApprovalDB db4 = new ApprovalDB(mContext, UserManager.getManager()
                .getUser().userId + "chat");
        long approvalnum = db4.getNewApprovalNum();
        EventDB db5 = new EventDB(mContext,
                UserManager.getManager().getUser().userId + "chat");
        long eventnum = db5.getNewEventNum();
        ChatMessageDB db6 = new ChatMessageDB(mContext, UserManager
                .getManager().getUser().userId + "chat");
        long atnum = db6.getNewChatMessageNum();

        AppContext.dspnum = (int) approvalnum;
        AppContext.rwnum = (int) tasknum;
        AppContext.mesnum = (int) messnum;
        AppContext.eventnum = (int) eventnum;
        AppContext.atnum = (int) atnum;
        // 消息提示数量由很多种类型的消息组成的
        num = messnum + draftnum + tasknum + approvalnum + eventnum + atnum;
    }

    private void setChatMessageNum() {
        int countTotal = (int) (EMChatManager.getInstance()
                .getUnreadMsgsCount());
        int countTotalhuanxin = (int) (EMChatManager.getInstance()
                .getUnreadMsgsCount());
////        int countTotal = (int) (num + EMChatManager.getInstance()
////                .getUnreadMsgsCount());
//        //待审批的数目计算
//        String num = RunTimeManager.getInstance().getDaiNum();
//        int numDaishenpi = 0;
//        if(num != null && !num.equals("")){
//            numDaishenpi = Integer.parseInt(num);
//        }
//        countTotal = countTotal +numDaishenpi;
        //通知中心数目
//        int messagenum= (int) RunTimeManager.getInstance().getMessageNx();
//        //云信+通知中心+待审批总数
//        countTotal = countTotal + messagenum;
        if (countTotalhuanxin > 0) {
            drop.setVisibility(View.VISIBLE);
            if (countTotal > 99) {
                drop.setVisibility(View.GONE);
                drop99.setVisibility(View.VISIBLE);
                BadgeUtil.setBadgeCount(getApplicationContext(), 99);
            } else {
                drop99.setVisibility(View.GONE);
                drop.setVisibility(View.VISIBLE);
                drop.setText("" + countTotalhuanxin);
                BadgeUtil.setBadgeCount(getApplicationContext(), countTotal);

            }
        } else {
            drop99.setVisibility(View.GONE);
            drop.setVisibility(View.GONE);
            // 应用图标清空
            BadgeUtil.resetBadgeCount(getApplicationContext());
        }
    }

    public class MyOnClickListener implements OnClickListener {
        private int index = 0;

        public MyOnClickListener(int i) {
            index = i;
        }

        @Override
        public void onClick(View v) {
            if (index == 2 && yuntieydao) {
                yuntieyindao.setVisibility(View.VISIBLE);
            } else {
                yuntieyindao.setVisibility(View.GONE);
            }
            if (index == 3 && tongshiydao) {
                tongshiyindao.setVisibility(View.VISIBLE);
            } else {
                tongshiyindao.setVisibility(View.GONE);
            }
            if (index == 4 && meydao) {
                meyindao.setVisibility(View.VISIBLE);
            } else {
                meyindao.setVisibility(View.GONE);
            }
            tabSelect(index);
        }
    }

    ;

    /**
     * 选择
     *
     * @param index
     */
    public void tabSelect(int index) {
        if (currentTab == index) {
            return;
        }
        // 设置选择后的效果
        setSelect(index);
        // 获得 将要展示的fragment
        Fragment fragment = fragments.get(index);
        FragmentTransaction ft = this.getSupportFragmentManager()
                .beginTransaction();
        if (currentTab < 0)
            currentTab = 0;
        fragments.get(currentTab).onPause(); // 暂停当前tab
        if (fragment.isAdded()) {
            fragment.onResume(); // 启动目标tab的onResume()
        } else {
            ft.add(R.id.frame, fragment);
        }
        ft.commit();
        showTab(index); // 显示目标tab

    }

    /**
     * 切换tab
     *
     * @param idx
     */
    @SuppressLint("Recycle")
    private void showTab(int idx) {
        for (int i = 0; i < fragments.size(); i++) {
            Fragment fragment = fragments.get(i);
            FragmentTransaction ft = this.getSupportFragmentManager()
                    .beginTransaction();
            ft.setCustomAnimations(R.anim.frag_slide_in_left,
                    R.anim.frag_slide_out_right);
            getSupportFragmentManager().beginTransaction().addToBackStack(null);
            if (idx == i) {
                ft.show(fragment);
            } else {
                ft.hide(fragment);
            }
            ft.commit();
        }
        currentTab = idx;
        invalidateOptionsMenu();
    }

    /**
     * 设置图标效果
     *
     * @param index
     */
    public void setSelect(int index) {
        switch (index) {
            case 0:// home
                xiaoxi_Text.setTextColor(getResources().getColor(R.color.hui));
                xiaoxi_image
                        .setImageResource(R.drawable.chater_index_message_transp);
                me_Text.setTextColor(getResources().getColor(R.color.hui));
                me_image.setImageResource(R.drawable.chatter_index_aboutme_transp);

                footer_cooperation_icon
                        .setImageResource(R.drawable.footer_tab_cooperation_nor);
                footer_cooperation_text.setTextColor(getResources().getColor(
                        R.color.hui));

                contaxt_text.setTextColor(getResources().getColor(R.color.hui));
                contaxt_image
                        .setImageResource(R.drawable.chatter_index_tongshi_transp);

                zhuye_text.setTextColor(getResources().getColor(
                        R.color.bottom_text_color_p));
                index_image.setImageResource(R.drawable.chatter_index_zhuye);
                break;
            case 1:// message
                zhuye_text.setTextColor(getResources().getColor(R.color.hui));
                index_image.setImageResource(R.drawable.chatter_index_zhuye_transp);
                me_Text.setTextColor(getResources().getColor(R.color.hui));
                me_image.setImageResource(R.drawable.chatter_index_aboutme_transp);

                footer_cooperation_icon
                        .setImageResource(R.drawable.footer_tab_cooperation_nor);
                footer_cooperation_text.setTextColor(getResources().getColor(
                        R.color.hui));

                contaxt_text.setTextColor(getResources().getColor(R.color.hui));
                contaxt_image
                        .setImageResource(R.drawable.chatter_index_tongshi_transp);
                xiaoxi_Text.setTextColor(getResources().getColor(
                        R.color.bottom_text_color_p));
                xiaoxi_image.setImageResource(R.drawable.chater_index_message);
                break;
            case 2:// message
                zhuye_text.setTextColor(getResources().getColor(R.color.hui));
                index_image.setImageResource(R.drawable.chatter_index_zhuye_transp);
                me_Text.setTextColor(getResources().getColor(R.color.hui));
                me_image.setImageResource(R.drawable.chatter_index_aboutme_transp);

                contaxt_text.setTextColor(getResources().getColor(R.color.hui));
                contaxt_image
                        .setImageResource(R.drawable.chatter_index_tongshi_transp);

                xiaoxi_Text.setTextColor(getResources().getColor(R.color.hui));
                xiaoxi_image
                        .setImageResource(R.drawable.chater_index_message_transp);

                footer_cooperation_icon
                        .setImageResource(R.drawable.footer_tab_cooperation_hover);
                footer_cooperation_text.setTextColor(getResources().getColor(
                        R.color.bottom_text_color_p));
                break;
            case 3:
                zhuye_text.setTextColor(getResources().getColor(R.color.hui));
                index_image.setImageResource(R.drawable.chatter_index_zhuye_transp);
                xiaoxi_Text.setTextColor(getResources().getColor(R.color.hui));

                xiaoxi_image
                        .setImageResource(R.drawable.chater_index_message_transp);
                footer_cooperation_icon
                        .setImageResource(R.drawable.footer_tab_cooperation_nor);
                footer_cooperation_text.setTextColor(getResources().getColor(
                        R.color.hui));

                me_Text.setTextColor(getResources().getColor(R.color.hui));
                me_image.setImageResource(R.drawable.chatter_index_aboutme_transp);
                contaxt_text.setTextColor(getResources().getColor(
                        R.color.bottom_text_color_p));
                contaxt_image.setImageResource(R.drawable.chatter_index_tongshi);
                break;
            case 4:
                zhuye_text.setTextColor(getResources().getColor(R.color.hui));
                index_image.setImageResource(R.drawable.chatter_index_zhuye_transp);
                xiaoxi_Text.setTextColor(getResources().getColor(R.color.hui));
                xiaoxi_image
                        .setImageResource(R.drawable.chater_index_message_transp);

                footer_cooperation_icon
                        .setImageResource(R.drawable.footer_tab_cooperation_nor);
                footer_cooperation_text.setTextColor(getResources().getColor(
                        R.color.hui));

                contaxt_text.setTextColor(getResources().getColor(R.color.hui));
                contaxt_image
                        .setImageResource(R.drawable.chatter_index_tongshi_transp);
                me_Text.setTextColor(getResources().getColor(R.color.bottom_text_color_p));
                me_image.setImageResource(R.drawable.chatter_index_aboutme);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        DialogUtils.Exit(mContext);
    }

    /**
     * 初始化消息推送，定位上传参数
     */
    public void initPushAndLocat() {

        ConfigManager configManager = ConfigManager.getInstance();
        Log.d("kaiqidingweifuwu",
                "shifoukaiqi:" + configManager.isAllowLocation());
        if (configManager.isAllowLocation()) {// 如果定位开启 就 开启定位
            Intent service = new Intent(this, DingWeiService.class);
            stopService(service);
            startService(service);
        }
        if (configManager.isAllowPush()) {
            CloudCCPushManager.getInstance().resumePushWork();
        } else {
            CloudCCPushManager.getInstance().stopPushWork();
        }
        // 后台绑定bingding
        Intent service = new Intent(this, BindingService.class);
        startService(service);
    }

    /**
     * 主页广播
     *
     * @author Administrator
     */
    class MyMessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (action.equals(AppContext.MESSAGE_SYSTEM)
                        || action.equals(AppContext.MESSAGE_CHATMESSAGE)
                        || action.equals(AppContext.MESSAGE_DAISHENPI)
                        || action.equals(AppContext.MESSAGE_DAIBANRENWU)
                        || action.equals(AppContext.MESSAGE_RICHENG_EVENT)
                        || action.equals(AppContext.TASK_NUM)
                        || action.equals(AppContext.EVENT_NUM)
                        || action.equals(AppContext.CAOGAO_NUM)
                        || action.equals(AppContext.DAISHENPI_NUM)
                        || action.equals(AppContext.MESSAGE_CHAT_NUM)
                        || action.equals(AppContext.MESSAGE_SYSTEM_NUM)) {// 来消息广播
                    try {
                        setMessageNum();
                        setChatMessageNum();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                } else if (action.equals(AppContext.SHEBEI_ZHUCE)) {// 设备注册
                    // push();
                } else if (action.equals(AppContext.UPDATE_USER_ICON)) {
                    menuUserLogo.setImageBitmap(AppContext.topicon);
                } else if (action.equals(AppContext.OPEN_FILE)) {
                    FileUtil.openFile(context, new File(AppContext.filePath));
                } else if (action.equals(AppContext.GET_WEIXIN_LOGIN)) {
                    // TODO loginWebView();// 小网页后台登陆
                } else if (action.equals(AppContext.WEB_TO_MENU)) {
                    tabSelect(0);
                    menu_foot.setVisibility(View.VISIBLE);
                    menuHome.setSelected(true);
                    menuSetting.setSelected(false);
                    module_list.setItemChecked(mGroupPosition + mChildPosition
                            + 1, false);
                    mGroupPosition = -1;
                }
            } catch (Exception e) {
                Tools.handle(e);
            }
        }
    }

    /**
     * 点击侧拉 的监听
     */
    @Override
    public boolean onChildClick(ExpandableListView parent, View v,
                                int groupPosition, int childPosition, long id) {
        Log.d("celajianting", "侧拉监听" + groupPosition + childPosition);
        // 设置 主页
        menuHome.setSelected(false);
        menuSetting.setSelected(false);
        menu_foot.setVisibility(View.VISIBLE);
        AppContext.iscomeMenu = true;
        MenuModel menuItem = mMenuAdapter.getGroup(groupPosition);
        MenuTabModel menuTab = mMenuAdapter.getChild(groupPosition,
                childPosition);
        AppContext.indexUrl = UrlManager.getRootUrl()
                + UrlTools.getModuleUrl(menuItem.id, menuItem.label);
        AppContext.urlString = UrlManager.getRootUrl()
                + UrlTools.getTabsUrl(menuTab, menuItem);
        menuHome.setSelected(true);
        menuSetting.setSelected(false);
        module_list.setItemChecked(mGroupPosition + mChildPosition + 1, false);
        mGroupPosition = -1;
        MenuManager.getInstance().enterMenuDetailOrList(menuTab, this);
        return true;
    }

    List<MenuModel> menusend = null;

    /**
     * 获得菜单成功
     *
     * @param event
     */
    public void onEventMainThread(MenuFillEvent event) {
        Log.d("celajianting", "主页数据传递回来");
        if (event.isError()) {
            Log.d("slidingceshi1", "主页数据返回错误");
            return;

        }
        menusend = new ArrayList<MenuModel>();
        List<MenuModel> menus = event.getData().data;
        Log.d("zhuyedaya", "主页数据：" + menus.size() + menus.get(0).tab.get(1).imageId);
        MenuManager.getInstance().filterMenus(menus);
        for (int i = 0; i < menus.size(); i++) {
            // menus.get(i).isshuaxin = false;
        }
        CacheManager.getInstance().cacheMenu(menus);

        menusend = menus;
        Log.d("slidingceshi", "数据加载全部" + menus.size());
        fillMenu(true, menus);

    }

    int slidingtag = 0;

    private void fillMenu(boolean refresh, List<MenuModel> menus) {

        int expId = 0;
        ccMenu = menus.get(0);
//		Log.d("fdwjf",ccMenu.tab.size());
        for (int i = 0; i < menus.size(); i++) {
            MenuModel menuItem = menus.get(i);
            // LogUtils.d("getstring3", "ccmenu"+ccMenu.tab.get(i).tab_name);
//			Log.d("slidingceshi", "chucuole");
            // Log.d("getstring3", menuItem.tab.get(i).tab_name);
            if (StringUtils.equals(menuItem.state, "1")) {// 默认打开
                ccMenu = menuItem;
//				Log.d("fdwjf","ssss::"+ccMenu.tab.size());
                expId = i;
                slidingtag = i;
            }
        }
        if (refresh || mMenuAdapter == null) {
            mMenuAdapter = new MyMenuAdapter(menus, this);
        }

        module_list.setAdapter(mMenuAdapter);
        module_list.setGroupIndicator(null);
        module_list.setOnChildClickListener(this);
        module_list.setOnGroupClickListener(groupListener);
        module_list.expandGroup(expId);

        // 通知主页更新
        Fragment fragment = null;
        try {
            fragment = fragments.get(0);
        } catch (Exception e) {
        }
        if (null != fragment && fragment instanceof MainUIFragment
                && fragment.isResumed() && refresh) {
            ccMenu.isshuaxin = true;
            ((MainUIFragment) fragment).initData();
            // zhuyeshuaxin event = new zhuyeshuaxin();
            // event.isshuaxin = true;
            // EventBus.getDefault().post(event);

        }

    }

    private OnGroupClickListener groupListener = new OnGroupClickListener() {

        @Override
        public boolean onGroupClick(ExpandableListView parent, View v,
                                    int groupPosition, long id) {
            if (sign == -1) {
                // 展开被选的group
                module_list.expandGroup(groupPosition);
                sign = groupPosition;
            } else if (sign == groupPosition) {
                module_list.collapseGroup(sign);
                sign = -1;
            } else {
//                module_list.collapseGroup(sign);
                // 展开被选的group
                module_list.expandGroup(groupPosition);
                sign = groupPosition;
            }
            return true;
        }
    };
    private int mActivityFrom;

    @Override
    public void register() {
        EventEngine.register(this);
    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }

    @Override
    protected void onDestroy() {
        EventEngine.uregister(this);
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {
            Tools.handle(e);
        }
        super.onDestroy();

        try {
            // 处理测试数据
            if (RunTimeManager.getInstance().isTestModel()) {
                AppManager.getInstance().clearTestModel();
            }
        } catch (Exception e) {
            Tools.handle(e);
        }

    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.shouye_menu:// 首页
                tabSelect(0);
                menu_foot.setVisibility(View.VISIBLE);
                menu.toggle();
                menuHome.setSelected(true);
                menuSetting.setSelected(false);
                int numberOfGroupThatIsOpened = 0;
                for (int i = 0; i < mGroupPosition; i++) {
                    if (module_list.isGroupExpanded(i)) {
                        numberOfGroupThatIsOpened += mMenuAdapter
                                .getChildrenCount(i);
                    }
                }
                module_list.setItemChecked(mGroupPosition + mChildPosition
                        + numberOfGroupThatIsOpened + 1, false);
                Log.d("clicked", "选择了：" + mGroupPosition + mChildPosition);
                mGroupPosition = -1;
                break;
            case R.id.shezhi_menu:
                Log.d("shezhi_menu", "点击了设置");
                menu_foot.setVisibility(View.GONE);
                SharedPreferences sp = getSharedPreferences("jump", 0);
                SharedPreferences.Editor editor = sp.edit();
                editor.clear();
                editor.putString("lyjs", "nObacks");
                editor.commit();
                tabSelect(5);
                menuHome.setSelected(false);
                menuSetting.setSelected(true);
                int numberOfGroupThatIsOpened2 = 0;
                for (int i = 0; i < mGroupPosition; i++) {
                    if (module_list.isGroupExpanded(i)) {
                        numberOfGroupThatIsOpened2 += mMenuAdapter
                                .getChildrenCount(i);
                    }
                }
                module_list.setItemChecked(mGroupPosition + mChildPosition
                        + numberOfGroupThatIsOpened2 + 1, false);
                Log.d("clicked1", "选择了：" + mGroupPosition + mChildPosition);
                menu.toggle();
                mGroupPosition = -1;
                break;

//            case R.id.userimg:
//                break;
            case R.id.phototext:
                showSelectImg();
                break;
            default:
                break;
        }
    }

    private void loginWebView() {
        webview = (WebView) findViewById(R.id.loginwebview);
        WebSettings webSettings = webview.getSettings();
        webSettings.setAllowFileAccess(true);
        webSettings.setJavaScriptEnabled(true);
        webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                int end = url.indexOf(";");
                String name;
                if (end != -1) {
                    name = url.substring(0, end);
                } else {
                    name = url;
                }
                if (name.equals(UrlTools.weixinUrl + UrlTools.loginWeb)
                        || name.equals(UrlTools.weixinUrl + "/main.action")
                        || name.equals(UrlTools.weixinUrl
                        + "/WeiXin_index.action")) {
                    AppContext.islogining = true;
                }
                super.onPageFinished(view, url);
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }
        });
        webview.loadUrl(UrlManager.getBindingUrl()
                + RunTimeManager.getInstance().getServerBinding());
    }

    /**
     * 显示头像图片选择
     */
    private void showSelectImg() {
        Intent intent = new Intent(MainUIActivity.this,
                SelectPictureActivity.class);
        startActivityForResult(intent, 70);
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //判断注册推送token
        if (CApplication.isTokenPush && UserManager.getManager().isLogin() && !TextUtils.isEmpty(CApplication.tokens)) {
            final PushEngine dao = new PushEngineImpl();
            // 设备注册
            CApplication.isTokenPush = false;
            new PushPresenter().registerBind(CApplication.tokens);
        }

        SharedPreferences sp = getSharedPreferences("jump", 0);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.putString("lyjs", "nObacks");
        editor.commit();
        try {
            setMessageNum();
            setChatMessageNum();
        } catch (Exception e) {
        }
        // 注册 消息监听
        EMChatManager.getInstance().registerEventListener(
                this,
                new EMNotifierEvent.Event[]{
                        EMNotifierEvent.Event.EventNewMessage,
                        EMNotifierEvent.Event.EventOfflineMessage,
                        EMNotifierEvent.Event.EventConversationListChanged});

    }

    @Override
    protected void onStop() {
        // 取消消息监听
        EMChatManager.getInstance().unregisterEventListener(this);
        setChatMessageNum();
        super.onStop();
    }

    /**
     * 消息接收到的时候
     */
    @Override
    public void onEvent(EMNotifierEvent event) {
        switch (event.getEvent()) {
            case EventNewMessage: // 普通消息
            {
                EMMessage message = (EMMessage) event.getData();
                IMHelper.getInstance().getNotifier().onNewMsg(message);
                toast.setTextNoImage(getString(R.string.yunxinmessage)).Short(getApplicationContext(),"").show(30,getApplicationContext());
                break;
            }

            case EventOfflineMessage: {
                break;
            }

            case EventConversationListChanged: {

                break;
            }
            default:
                break;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setChatMessageNum();
                refreshMessage();

            }
        });

    }

    private void refreshMessage() {
        if (currentTab == 3) {
            ((NewCoworkerListFragment) fragments.get(3)).Imsets();
//            ((MainMessageFragment) fragments.get(1)).Imset();
        }
    }

    //通知刷新
    private void refreshMessageTz() {
//        initRequestDataTz();
        switch (currentTab) {
            case 0:
                ((MainUIFragment) fragments.get(0)).MessageSetNCL();
                break;
            case 1:
                ((MainMessageFragment) fragments.get(1)).MessageSetNCL();
                break;
            case 2:
                ((DynamicMainFragment) fragments.get(2)).MessageSetNCL();
                break;
            case 3:
                ((NewCoworkerListFragment) fragments.get(3)).Imsets();
                break;
            case 4:
                ((Newmainmefragments) fragments.get(4)).MessageSetNCL();
                break;

        }
    }

    /**
     * 登录聊天
     */
    private void loginIM() {
        // 获取用户名
        UserModel user = UserManager.getManager().getUser();
        final String hxUserName = ContactsManager.getInstance()
                .encodeHXuserName(user.userId);
        LogUtils.d("imchat", "登录帐号:" + hxUserName);
        // 使用userId登录
        if (IMHelper.getInstance().isLoggedIn()
                && StringUtils.equals(IMHelper.getInstance()
                .getCurrentUsernName(), hxUserName)) {
            LogUtils.d("imchat", "已经登录了。。");
            loadIMData();
            return;
        }
        PreferenceManager.getInstance().removeCurrentUserInfo();

        EMChatManager.getInstance().login(hxUserName, "szydcloudcc",
                new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        LogUtils.d("imchat", "登录成功。。");
                        // 登陆成功，保存用户名
                        IMHelper.getInstance().setCurrentUserName(hxUserName);
                        // 注册群组和联系人监听
                        IMHelper.getInstance()
                                .registerGroupAndContactListener();

                        // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                        // ** manually load all local groups and

                        // 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                        // boolean updatenick =
                        // EMChatManager.getInstance().updateCurrentUserNick(
                        // DemoApplication.currentUserNick.trim());
                        // if (!updatenick) {
                        // Log.e("LoginActivity",
                        // "update current user nick fail");
                        // }
                        // 异步获取当前用户的昵称和头像(从自己服务器获取，demo使用的一个第三方服务)
                        // DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
                        // 获取cloucc服务器的通讯录
                        loadIMData();
                    }

                    @Override
                    public void onProgress(int progress, String status) {
                    }

                    @Override
                    public void onError(final int code, final String message) {
                        // LogUtils.d("imchat", "登录失败:"+hxUserName);
                        // runOnUiThread(new Runnable() {
                        // public void run() {
                        // Toast.makeText(
                        // getApplicationContext(),
                        // getString(R.string.Login_failed)
                        // + message, Toast.LENGTH_SHORT)
                        // .show();
                        // }
                        // });
                    }
                });
    }

    private void loadIMData() {
        LogUtils.d("imchat", "开始loading。。");
        EMGroupManager.getInstance().loadAllGroups();
        EMChatManager.getInstance().loadAllConversations();
        long queryCount = OrmManager.getManager().getOrm()
                .queryCount(CoworkerEntity.class);
        if (queryCount < 5) {
            ContactsManager.getInstance().syncContactes();
        }
    }

    /**
     * 获得 ccmenu 子菜单列表
     *
     * @return
     */
    public static MenuModel getCCMenuItems() {

        return ccMenu;
    }

    public List<MenuModel> getSendmenus() {
        return menusend;
    }

    /**
     * 注销登录
     *
     * @param context
     */
    public void showClearLogin(final Context context) {
        String mEns = RunTimeManager.getInstance().getlanguage();
        String zhuxiao = "";
        String zx = "亲！确认注销吗？";
        if ("en".equals(mEns)) {
            zhuxiao = "Log Out";
            zx = "Are you sure you want to log out?";
        } else {
            zhuxiao = "注销账户";
            zx = "亲！确认注销吗？";
        }
        DialogUtilsZhuXiao.showWarn(mContext, zhuxiao,
                zx, new DialogUtilsZhuXiao.DialogOnClickListeners() {
                    @Override
                    public void onClickPositive(final Dialog dialog) {
                        // 退出环信
                        IMHelper.getInstance().logout(false, new EMCallBack() {

                            @Override
                            public void onSuccess() {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        loginOut();

                                    }
                                });
                            }

                            @Override
                            public void onProgress(int arg0, String arg1) {

                            }

                            @Override
                            public void onError(int arg0, String arg1) {
                                dialog.cancel();
                            }
                        });

                    }

                    @Override
                    public void onClickNegative(Dialog dialog) {
                        dialog.cancel();
                    }
                });
    }


    private void loginOut() {
        CacheManager.getInstance().clear();
        UserManager.getManager().clearUser();
        RunTimeManager.getInstance().clearUserCache();
        ContactsManager.getInstance().clearContactCache();
        AsyncClient.getInstance().clear(mContext);
        UserManager.getManager().savezhuxiao(true);
        Intent intent = new Intent(mContext, LoginNewActivity.class);
        intent.putExtra("page.index", 5);
        mContext.startActivity(intent);
        // finish();aaa
        AppManager.getInstance().AppExit();
    }

    public int setInt() {

        return mFrom;

    }

    /**
     * 拨打电话
     *
     * @param context
     */
    public void showCallPhone(final Context context) {
        String mEns = RunTimeManager.getInstance().getlanguage();
        String zhuxiao = "";
        String zx = "亲！确认注销吗？";
        if ("en".equals(mEns)) {
            zhuxiao = "Telephone";
            zx = "Dear！ Make sure you dial the number ?";
        } else {
            zhuxiao = "电话";
            zx = "亲！确认拨打电话？";
        }
        com.cloudcc.mobile.weight.DialogUtils.showWarn(mContext, zhuxiao,
                zx, new DialogOnClickListener() {
                    @Override
                    public void onClickPositive(final Dialog dialog) {
                        Intent intent = new Intent(Intent.ACTION_CALL);
                        Uri data = Uri.parse("tel:" + "4006422008");
                        intent.setData(data);
                        startActivity(intent);

                    }

                    @Override
                    public void onClickNegative(Dialog dialog) {
                        dialog.cancel();
                    }
                });
    }

    public void setHttp() {

        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "getChatterSetup");
        Log.d("列表值url-------------------------", UrlManager.getInterfaceUrl()
                + "?binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&serviceName=getLookupValue"
                + "&objectId=2016360343BD7B2SQ2PO" + "&pageSize=1"
                + "&keyword=");
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {

                        Log.d("列表值接口失败-------------------------", arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        Log.d("列表值接口成功-------------------------", arg0.result);
                        Gson gson = new Gson();
                        Qxbeau mDdata = gson.fromJson(arg0.result.toString(),
                                Qxbeau.class);
                        qxyuntie = mDdata.getData().getChattersetup();
                        android.util.Log.i("TAG", "aaaaaaaaa" + mDdata);

                        if ("false".equals(qxyuntie)) {
                            footer_cooperation_container.setVisibility(View.GONE);
                        } else {
                            footer_cooperation_container.setVisibility(View.VISIBLE);
                        }
                    }
                });

    }

    private void intentAbout() {
        aboutPersion.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                menu.toggle(false);
                Intent intent = new Intent(MainUIActivity.this, Myinformation.class);
                SaveTemporaryData.mSmart = "";

                intent.putExtra("userId", RunTimeManager.getInstance().getUserId());
                intent.putExtra("isme", "shouye");
                intent.putExtra("name", UserManager.getManager().getUser().userName);
                startActivity(intent);
//                tabSelect(4);
            }
        });
    }

    private void initRequestDataTz() {
        xlsx_x_bsr.postDelayed(new Runnable() {
            @Override
            public void run() {
                xlsx_x_bsr.autoRefresh(true);
            }
        }, 150);
    }

    private void initRefreshTz() {
        xlsx_x_bsr.setLoadingMinTime(1000);
        xlsx_x_bsr.setPtrHandler(this);
        PtrClassicDefaultHeader header = new PtrClassicDefaultHeader(mContext);
//        final MyHeader header = new MyHeader(mContext);
//        int[] colors = getResources().getIntArray(R.array.google_colors);
//        header.setColorSchemeColors(colors);
//        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
//        header.setPadding(0, DensityUtils.dpToPixel(mContext, 10), 0,
//                DensityUtils.dpToPixel(mContext, 5));
//        header.setPtrFrameLayout(xlsx_x_bsr);
        header.setbg();
        xlsx_x_bsr.setHeaderView(header);
        xlsx_x_bsr.addPtrUIHandler(header);

    }


    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, xmListview, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        initMessage();
//        tzadapter_x = new SlidingRightAdapter(messsageList, this);
//        xmListview.setAdapter(tzadapter_x);
//        xlsx_x_bsr.refreshComplete();
    }

    private void initMessage() {
//        PushSaveMessageDB db = new PushSaveMessageDB(this, UserManager
//                .getManager().getUser().userId + "pushsavemessage");
////        messsageList = new ArrayList<>();
//        try {
//            messsageList = db.findAllPushSaveMessage(PushSaveMessage.class);
//            if (messsageList == null) {
//                messsageList = new ArrayList<>();
//            } else {
//                Collections.reverse(messsageList);
//            }
//
//        } catch (DbException e) {
//            e.printStackTrace();
//        }

        event = new BeauEventList.BeauTongzhiEvent();
        tongzhiImpl.tongzhiDate(event);
    }
    public void onEventMainThread(BeauEventList.BeauTongzhiEvent event) {
        if (event.isError()) {
            return;
        }
        List<BeauTongzhi> tongzhiLi = event.getData();
        tzadapter_x = new SlidingRightAdapter(tongzhiLi,mContext);
        xmListview.setAdapter(tzadapter_x);
        xlsx_x_bsr.refreshComplete();

        long a = 0;
        for (int i = 0;i<tongzhiLi.size();i++){
            if("0".equals(tongzhiLi.get(i).status)) {
                a ++;
            }
        }
        RunTimeManager.getInstance().setMessageNx(a);
        EventEngine.post(new MessageNumX(a));
    }
    private void initMessageNum() {
        //将通知装进本地数据库

        long b = 0;
        try {
            PushSaveMessageDB db = new PushSaveMessageDB(this, UserManager
                    .getManager().getUser().userId + "pushsavemessage");
            //消息数
            b = 0;
            if (db.isExit()) {
                b = db.getNewPushSaveMessageNum();
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
//        EventEngine.post(new MessageNumX(b));
//        RunTimeManager.getInstance().setMessageNx(b);

    }

}
